package com.example.vae.Home.Home;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProviders;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.vae.Adapter.DongtaiImgPagerAdapter;
import com.example.vae.Adapter.MyFragmentPageAdapter;
import com.example.vae.DongtaiViewModel;
import com.example.vae.Home.Home.dongtai.quanbu;
import com.example.vae.Home.Home.dongtai.shiping;
import com.example.vae.Home.Home.dongtai.tuji;
import com.example.vae.Home.Home.dongtai.xingwen;
import com.example.vae.Home.Home.dongtai.zhuanfang;
import com.example.vae.R;
import com.example.vae.databinding.DongtaiFragmentBinding;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.List;

public class dongtaiFragment extends Fragment{

    private DongtaiViewModel mViewModel;
    private DongtaiFragmentBinding binding;

//    加载五个页面的数据源
    private TabLayout tabLayout;
    private ViewPager vp2;
    private List<Fragment> list=new ArrayList<>();
    private MyFragmentPageAdapter fragmentPagerAdapter;
    final  String[] titles={"全部","新闻","专访","图集","视频"};


//加载轮播图的数据源
    private int[] imgae_ids = new int[]{R.id.page_dongtai_1,R.id.page_dongtai_2,R.id.page_dongtai_3,R.id.page_dongtai_4};

    private ViewPager mViewPager;
    private TextView mTvPagerTitle;

    private List<ImageView> mImageList;//轮播的图片集合
    private String[] mImageTitles;//标题集合
    private int previousPosition = 0;//前一个被选中的position
    private List<View> mDots;//小点

    private boolean isStop = false;//线程是否停止
    private  int[] points_id=new int[]{R.id.points_1,R.id.points_2,R.id.points_3,R.id.points_4,R.id.points_5,R.id.points_6};

    public static dongtaiFragment newInstance() {
        return new dongtaiFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        mViewModel = ViewModelProviders.of(requireActivity()).get(DongtaiViewModel.class);
        binding = DataBindingUtil.inflate(inflater, R.layout.dongtai_fragment, container, false);
        binding.setData(mViewModel);
//        设置数据变化 的观察
        binding.setLifecycleOwner(requireActivity());

//        这里的加载五个活动页面
        list.add(new quanbu());
        list.add(new xingwen());
        list.add(new zhuanfang());
        list.add(new tuji());
        list.add(new shiping());

        vp2=binding.vp2;
        fragmentPagerAdapter=new MyFragmentPageAdapter(getFragmentManager(),0,list,titles);
        vp2.setAdapter(fragmentPagerAdapter);
        tabLayout=binding.tab;
        tabLayout.setupWithViewPager(vp2);
        tabLayout.getTabAt(1).select();


        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        init();

        // TODO: Use the ViewModel
    }

    /**
     * 第一步、初始化控件
     */
    public void init() {
        mViewPager =binding.vpImg;
        mTvPagerTitle = binding.loopDec;
        initData();//初始化数据
        initView();//初始化View，设置适配器

        new Thread(){
            public void run(){
                isStop = true;
                while(isStop){
                    try{
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //下一条
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mViewPager.setCurrentItem(mViewPager.getCurrentItem()+1);
                        }
                    });
                }
            }
        }.start();


    }

    /**
     * 第二步、初始化数据（图片、标题、点击事件）
     */
    public void initData() {

        //初始化标题列表和图片资源
        mImageTitles = new String[]{"这是一个好看的标题1","这是一个优美的标题2","这是一个快乐的标题3","这是一个开心的标题4"};
        int[] imageRess = new int[]{R.drawable.dongtai_1,R.drawable.dongtai_2,R.drawable.dongtai_3,R.drawable.dongtai_4};

        //添加图片到图片列表里
        mImageList = new ArrayList<>();
        ImageView iv;
        View dotView;
        LinearLayout.LayoutParams layoutParams;
        for (int i = 0; i < imageRess.length; i++) {
            iv = new ImageView(getContext());
            iv.setBackgroundResource(imageRess[i]);//设置图片
            iv.setId(imgae_ids[i]);//顺便给图片设置id
            iv.setOnClickListener(new pagerImageOnClick());//设置图片点击事件
            mImageList.add(iv);

            //加引导点
            dotView = new View(getContext());
            dotView.setBackgroundResource(R.drawable.dot);
            dotView.setId(points_id[i]);
            layoutParams = new LinearLayout.LayoutParams(24,24);
            if(i!=0){
                layoutParams.leftMargin=10;
            }
            //设置默认所有都不可用
            dotView.setEnabled(false);
            binding.lineLayoutDot.addView(dotView,layoutParams);

        }
    }

    //图片点击事件
    private class pagerImageOnClick implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.page_dongtai_1:
                    Toast.makeText(getContext(), "图片1被点击", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.page_dongtai_2:
                    Toast.makeText(getContext(), "图片2被点击", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.page_dongtai_3:
                    Toast.makeText(getContext(), "图片3被点击", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.page_dongtai_4:
                    Toast.makeText(getContext(), "图片4被点击", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }
    /**
     *  第三步、给PagerViw设置适配器，并实现自动轮播功能
     */
    public void initView(){
       DongtaiImgPagerAdapter viewPagerAdapter = new DongtaiImgPagerAdapter(mImageList, mViewPager);
        mViewPager.setAdapter(viewPagerAdapter);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //伪无限循环，滑到最后一张图片又从新进入第一张图片
                int newPosition = position % mImageList.size();
                // 把当前选中的点给切换了, 还有描述信息也切换
                mTvPagerTitle.setText(mImageTitles[newPosition]);//图片下面设置显示文本
                //设置轮播点
                binding.lineLayoutDot.getChildAt(newPosition).setEnabled(true);
                binding.lineLayoutDot.getChildAt(previousPosition).setEnabled(false);

                // 把当前的索引赋值给前一个索引变量, 方便下一次再切换.
                previousPosition = newPosition;

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        setFirstLocation();
    }

    /**
     * 第四步：设置刚打开app时显示的图片和文字
     */
    private void setFirstLocation() {
        mTvPagerTitle.setText(mImageTitles[previousPosition]);
        // 把ViewPager设置为默认选中Integer.MAX_VALUE / t2，从十几亿次开始轮播图片，达到无限循环目的;
        int m = (Integer.MAX_VALUE / 2) % mImageList.size();
        int currentPosition = Integer.MAX_VALUE / 2 - m;
        mViewPager.setCurrentItem(currentPosition);
    }

}
